<template>
  <view>
    <!--  评论弹窗  -->
    <up-popup mode="bottom" :customStyle="{ width: '100vw', maxheight: '80vh', zIndex: 999 }"
      v-model:show="isCommentModalVisible">
      <view class="ding-comment-modal">
        <!-- 头部 -->
        <view class="modal-header">
          <text class="header-title">{{ CommentName }}</text>
          <up-icon name="close" @click="closeCommentModal" class="close-icon"></up-icon>
        </view>

        <!-- 输入区域 -->
        <view class="comment-input-area">
          <textarea class="comment-textarea" placeholder="请输入评论内容（支持@人员）" v-model="commentText" maxlength="300"
            @input="handleInput" @confirm="submitComment" :focus="false" :auto-focus="false" :adjust-position="false"
            cursor-spacing="20" ref="commentTextarea"></textarea>

          <!-- 已@人员列表 -->
          <view class="mentioned-users" v-if="customInputMentions.length > 0">
            <view v-for="(user, index) in customInputMentions" :key="index" class="mentioned-user">
              <text>@{{ user.name }}</text>
              <up-icon name="close" size="12" @click="removeMention(index)" class="remove-mention"></up-icon>
            </view>
          </view>

          <!-- 上传的图片预览-->
          <view class="upload-preview" v-if="uploadimgList.length > 0">
            <view class="preview-title">图片</view>
            <view class="image-grid">
              <view v-for="(img, index) in uploadimgList" :key="img.id" class="image-item">
                <image :src="img.url" mode="scaleToFill" class="preview-image"
                  @click="ImgviewClick(uploadimgList, img, 'pl')">
                </image>
                <view class="remove-btn" @click="removeuploadimgList(index)">
                  <up-icon name="close-circle-fill" size="20" color="#ff4d4f"></up-icon>
                </view>
              </view>
            </view>
          </view>

          <!-- 上传的文件预览 -->
          <view class="upload-preview" v-if="uploadFilesList.length > 0">
            <view class="preview-title">文件</view>
            <view class="file-list">
              <view v-for="(file, index) in uploadFilesList" :key="file.id" class="file-item"
                @click="FileViewClick(uploadFilesList, file)">

                <view class="file-info">
                  <text class="file-name" :title="file.name">{{ truncateMiddle(file.name) }}</text>
                </view>
                <view class="remove-btn" @click.stop="removeuploadFilesList(index)">
                  <up-icon name="close-circle-fill" size="20" color="#ff4d4f"></up-icon>
                </view>
              </view>
            </view>
          </view>

          <!-- 底部工具栏 -->
          <view class="toolbar" v-show="passonType == 1">
            <view class="toolbar-left">
              <view class="tool-item" @click="chooseImage">
                <up-icon name="photo" size="22" color="#666"></up-icon>
              </view>

              <view class="tool-item" style="position: relative;left: 40rpx;width: 100px;">

                <commentFileUpload @applyOrderDetailuploadEnd="applyOrderDetailuploadEnd" style="z-index: 9999;">
                </commentFileUpload>
              </view>
            </view>
            <text class="word-count">{{ commentText.length }}/300</text>
          </view>
        </view>


        <!-- 发送按钮 -->
        <view class="send-btn-wrapper">
          <view class="send-btn"
            :class="{ active: commentText.trim().length > 0 || uploadimgList.length > 0 || uploadFilesList.length > 0 }"
            @click="submitComment">
            发送
          </view>
        </view>
      </view>
    </up-popup>


    <!-- 图片预览弹窗 -->
    <image-preview :show="showImagePreview" :imageList="previewImageList" :currentIndex="previewCurrentIndex"
      @update:show="showImagePreview = $event" @close="closeImagePreview" @indexChange="onPreviewIndexChange" />
  </view>
</template>

<script>
import { COMMON_API_BASE_URL } from '@/utils/request'
import commentFileUpload from '@/pages/apply/form/components/commentFileUpload.vue'
import apply from "@/apis/cloud/apply.js"
import modalindex from '@/components/Operationboxpublic/modalindex.vue'
import ImagePreview from './ImagePreview.vue'
import { ProcessingURL, viewFile, } from '@/utils/publicmethod.js'
export default {
  name: 'commentPopup',

  props: {
    formData: {
      type: Object,
      default: {}
    },
    userStore: {
      type: Object,
      default: {}
    },
    nextCloud: {
      type: String,
      default: ''
    },
    orderId: {
      type: String,
      default: ''
    },
  },
  components: {
    modalindex,
    commentFileUpload,
    ImagePreview
  },
  data () {
    return {
      isCommentModalVisible: false,
      customInputMentions: [], // 评论@的人员
      uploadimgList: [

      ], // 图片列表
      uploadFilesList: [], // 上传的文件列表
      passonList: [],
      CommentName: '',
      commentText: '', // 输入的文字
      passonType: '',
      oldContent: '', // 记录输入的文字
      showImagePreview: false,
      previewImageList: [],
      previewCurrentIndex: 0
    }
  },
  created () {
    uni.$on('applyOrderDetail', (data) => {
      this.selected(data)
    })
  },
  methods: {
    selected (users) {
      console.log('users', users);

      if (!Array.isArray(users)) return;

      const isUserExist = (user) => {
        return this.customInputMentions.some(
          existing => existing.id === user.id && existing.name === user.name
        );
      };

      const newUsers = users.filter(user => !isUserExist(user));

      if (newUsers.length === 0) {
        uni.showToast({ title: '该用户已被添加', icon: 'none' });
        this.renyuanshow = false;
        return;
      }


      // 获取光标前后的文本内容
      const textBeforeCursor = this.commentText.slice(0, this.mentionCursorPosition - 1);
      const textAfterCursor = this.commentText.slice(this.mentionCursorPosition);

      // 构建 @人员文本
      const mentionsText = users.map(user => `@${user.name}`).join(' ');

      // 更新评论文本
      this.commentText = `${textBeforeCursor}${mentionsText} ${textAfterCursor}`.trim();

      // 更新 @人员列表
      this.customInputMentions = [...this.customInputMentions, ...users];

      // 隐藏人员选择弹窗
      this.renyuanshow = false;
    },
    // 处理输入事件
    handleInput (event) {
      const text = event.detail.value;
      const cursorPosition = event.detail.cursor;
      const isDeleting = text.length < this.oldContent.length;
      if (isDeleting) {
        for (let i = 0; i < this.customInputMentions.length; i++) {
          const mention = this.customInputMentions[i];
          const mentionText = `@${mention.name}`;
          const beforeCursor = this.oldContent.slice(0, cursorPosition + 1);
          const mentionIndex = beforeCursor.lastIndexOf(mentionText);
          // 宽松判断光标是否刚好在 @xxx 后面或中间
          if (
            mentionIndex !== -1 &&
            cursorPosition <= mentionIndex + mentionText.length &&
            cursorPosition >= mentionIndex
          ) {
            // 删除 textarea 文本中 @xxx
            this.commentText = this.oldContent.replace(
              new RegExp(`\\s*${mentionText}\\s*`, 'g'),
              ' '
            ).trim();
            // 移除 mention 数据
            this.customInputMentions.splice(i, 1);
            this.oldContent = this.commentText;
            return;
          }
        }
      }
      // 检测输入了 @
      const lastChar = text[cursorPosition - 1];
      if (!isDeleting && lastChar === '@') {
        this.mentionCursorPosition = cursorPosition;
        // this.renyuanshow = true;

        uni.navigateTo({
          url: '/components/OrgPicker/index?overlay=false&entry=component&VisibleandHidden=true&title=人员选择&type=user&multiple=false&source=applyOrderDetail'
        });
      }
      this.commentText = text;
      this.oldContent = text;
      // 别删错了 mentions，只删已经不存在于文本中的
      this.customInputMentions = this.customInputMentions.filter(user => {
        return text.includes(`@${user.name}`);
      });
    },
    async submitComment () {
      if (this.isSubmitting) {
        return;
      }
      const hasCommentText = this.commentText.trim().length > 0;
      const hasImages = this.uploadimgList.length > 0;
      const hasFiles = this.uploadFilesList.length > 0;

      if ((!hasCommentText && !hasImages && !hasFiles) && this.passonType !== 2) {
        uni.showToast({
          title: '评论内容不能为空',
          icon: 'error',
        });
        return
      }

      this.isSubmitting = true;
      const imgIds = this.uploadimgList.map(img => img.id).join(',');

      const fileIds = this.uploadFilesList.map(file => file.id).join(',');

      uni.showLoading({
        title: '提交中...',
      });

      try {
        this.customInputMentions = this.customInputMentions.map(item => {
          return {
            jobNumber: item.id,
            name: item.name
          };
        });

        const result = await apply.Applypublish({
          id: this.orderId,
          content: this.commentText,
          aite: this.passonType == 1 ? JSON.stringify(this.customInputMentions) : '[]',
          file: fileIds,
          img: imgIds,
          type: this.passonType,
          forward_worker_id: this.passonType == 1 ? '' : `${this.passonList[0].id}`
        });

        if (result.status > 0) {
          uni.showToast({
            title: this.passonType == 1 ? '评论成功' : '转交成功',
            icon: 'success',
          });
          if (this.passonType == 2) {
            uni.$emit('getFormData')
          }
          this.$emit('getFormData')
          this.closeCommentModal(); // 关闭弹窗
        } else {
          uni.showToast({
            title: this.passonType == 1 ? '评论失败' : '转交失败',
            icon: 'error',
          });
        }
      } catch (error) {
        console.error('提交评论失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'error',
        });
      } finally {
        this.isSubmitting = false;
        uni.hideLoading();
      }
    },
    // 移除@的人员
    removeMention (index) {
      const user = this.customInputMentions[index];
      const mentionText = `@${user.name}`;

      this.commentText = this.commentText.replace(
        new RegExp(`\\s*${mentionText}\\s*`, 'g'),
        ' '
      ).trim();

      this.customInputMentions.splice(index, 1);
      this.oldContent = this.commentText;
    },
    ImgviewClick (item, img, val) {
      let imgList = [];
      let index = 0;

      // 确保图片的完整 URL
      img.url = ProcessingURL(img.url || img.path);

      if (val === 'pl') {
        item?.forEach((aitem) => {
          if (aitem?.url || aitem?.path) {
            const fullUrl = ProcessingURL(aitem.url || aitem.path);
            imgList.push(fullUrl);
          }
        });

        index = imgList.findIndex(url => url === img.url);
      } else {
        if (item?.value) {
          item.value.forEach((aitem) => {
            if (aitem?.url || aitem?.path) {
              const fullUrl = ProcessingURL(aitem.url || aitem.path);
              imgList.push(fullUrl);
            }
          });
        } else {
          item?.forEach((aitem) => {
            if (aitem?.url || aitem?.path) {
              const fullUrl = ProcessingURL(aitem.url || aitem.path);
              imgList.push(fullUrl);
            }
          });
        }

        // 确保比较的一致性
        const fullImgUrl = ProcessingURL(img.url || img.path);
        index = imgList.findIndex(url => url === fullImgUrl);
      }

      if (index === -1) index = 0;

      // #ifdef APP-PLUS
      uni.previewImage({
        current: index,
        urls: imgList,
        showmenu: true
      });
      //#endif

      // #ifdef H5
      this.previewImageList = imgList
      this.previewCurrentIndex = index
      this.showImagePreview = true
      // #endif
    },
    // 删除评论图片
    removeuploadimgList (index) {
      this.uploadimgList.splice(index, 1);
    },
    // 查看文件
    FileViewClick (data, item) {
      viewFile(item, {
        fileList: data, // 传入整组文件，实现图片多图预览
        userStore: this.userStore,
        xtoken: this.nextCloud?.xtoken,
      });
    },
    // 删除评论文件
    removeuploadFilesList (index) {
      this.uploadFilesList.splice(index, 1);
    },
    // 选择图片
    chooseImage () {
      const that = this;

      uni.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          uni.showLoading({
            title: '加载中...'
          });
          const tempFiles = res.tempFilePaths; // 选中的临时文件路径数组

          tempFiles.forEach((filePath) => {
            uni.uploadFile({
              url: `${COMMON_API_BASE_URL}/dist/interface/public/index.php/form/Form/upload`,
              filePath: filePath,
              name: 'file',
              formData: {
                token: uni.getStorageSync('token') || ''
              },
              success: (uploadRes) => {
                try {
                  const data = JSON.parse(uploadRes.data);
                  if (data.code === 0 || data.status > 0) {
                    that.uploadimgList.push({
                      type: data.data.type,
                      url: ProcessingURL(data.data.url),
                      name: data.data.name,
                      id: data.data.id,
                      size: data.data.size
                    });
                    uni.$u.toast('上传成功');
                  } else {
                    uni.showToast({
                      title: '上传失败',
                      icon: 'error'
                    });
                  }
                  uni.hideLoading();
                } catch (err) {
                  uni.hideLoading();
                  console.error('上传返回格式错误:', err);
                  uni.showToast({
                    title: '上传出错',
                    icon: 'error'
                  });
                }

              },
              fail: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '上传失败',
                  icon: 'error'
                });
              }
            });
          });
        }
      });
    },
    applyOrderDetailuploadEnd ({ fileList, index }) {
      this.uploadFilesList = fileList
    },
    commentPopupClick (value) {
      this.CommentName = value.CommentName
      this.passonType = value.passonType
      this.commentText = value.commentText
      this.customInputMentions = value.customInputMentions
      this.uploadimgList = value.uploadimgList
      this.uploadFilesList = value.uploadFilesList
      this.passonList = value.passonList
      this.isCommentModalVisible = true
    },
    closeCommentModal () {
      this.isCommentModalVisible = false
    },
    truncateMiddle (text, maxLength = 20) {
      if (text.length <= maxLength) return text;
      const half = Math.floor(maxLength / 2.5);
      return `${text.slice(0, half)}...${text.slice(-half)}`;
    },
    destroyClick () {
      uni.$off('applyOrderDetail');
    },

    // 关闭图片预览
    closeImagePreview () {
      this.showImagePreview = false
      this.previewImageList = []
      this.previewCurrentIndex = 0
    },

    // 预览索引变化
    onPreviewIndexChange (index) {
      this.previewCurrentIndex = index
    },

  }
}
</script>


<style lang="scss" scoped>
@import "../applyOrderDetail.scss";
</style>